package com.easymin.weixin.common.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.common.DataGrid;
import com.easymin.weixin.common.SignHelper;
import com.easymin.weixin.controller.v4.ResultTransport;
import com.easymin.weixin.entity.area.ChargeStartTime;
import com.easymin.weixin.entity.passenger.Passenger;
import com.easymin.weixin.entity.zhuanche.Order;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.Map.Entry;


@Component
@SuppressWarnings("all")
public class ZhuanApi {
  
  private static final Logger logger = LoggerFactory.getLogger(ZhuanApi.class);

  @Value("${module.zhuan.url}")
  private String zhuanApiGateway;

  @Value("${module.zhuan.appId}")
  private String zhuanAppId;

  @Value("${module.zhuan.appKey}")
  private String zhuanAppKey;

  @Autowired
  private RestTemplate restTemplate;

  @Autowired
  private PassengerApi passengerApi;

  @Autowired
  private DaijiaApi daijiaApi;
  /**
   * 创建订单.
   */
  public static final String CREATE =
      "api/orders/create.json?passengerId={passengerId}&passengerName={passengerName}"
      + "&passengerPhone={passengerPhone}&showPhone={showPhone}&companyId={companyId}"
      + "&companyName={companyName}&carTypeId={carTypeId}&channelName={channelName}"
      + "&startAddress={startAddress}&startLat={startLat}&startLng={startLng}"
      + "&serverTime={serverTime}&prePay={prePay}&appKey={appKey}&appId={appId}&sign={sign}";

  /**
   * 根据ID查询订单.
   */
  public static final String FIND_BY_ID =
      "api/orders/findByOrderId.json?orderId={orderId}&appKey={appKey}&appId={appId}&sign={sign}";

  public static final String FIND_BY_PARAM =
      "api/orders.json?passengerId={passengerId}&status={status}&orderby={orderby}&page={page}"
      + "&rows={rows}&appKey={appKey}&appId={appId}&sign={sign}";
  /**
   * 查询汽车类型.
   */
  public static final String FIND_CARTYPE =
      "api/carType/findCarType?appKey={appKey}&appId={appId}&sign={sign}";
  /**
   * 催促订单进度.
   */
  public static final String HASTEN_ORDER =
      "api/orders/hasten.json?orderId={orderId}&appKey={appKey}&appId={appId}&sign={sign}";
  /**
   * 查询车辆类型.
   */
  public static final String GET_CARTYPEV4 =
      "api/orders/v4up/queryCarTypes?companyId={companyId}&appKey={appKey}";
  /**
   * 查询收费标准.
   */
  public static final String QUERY_AREABYTYPEID =
      "api/orders/v4up/queryServiceTypeById?typeId={typeId}&appKey={appKey}";
  /**
   * 根据groupId查询订单.
   */
  public static final String FIND_BYGROUPID =
      "api/orders/v4up/findByGroupId?groupId={groupId}&appKey={appKey}";
  /**
   * 专车下单.
   */
//  public static final String CREATE_ZCORDER =
//      "api/orders/v4up/create?passengerId={passengerId}&passengerPhone={passengerPhone}"
//      + "&passengerName={passengerName}&userPhone={userPhone}&companyId={companyId}"
//      + "&companyName={companyName}&channelName={channelName}&serverTime={serverTime}"
//      + "&startAddress={startAddress}&startAddressDetail={startAddressDetail}&startLat={startLat}"
//      + "&startLng={startLng}&endAddress={endAddress}&endAddressDetail={endAddressDetail}"
//      + "&endLat={endLat}&endLng={endLng}&travelTime={travelTime}&mileage={mileage}"
//      + "&prePay={prePay}&flightNo={flightNo}&trainNo={trainNo}&serviceType={serviceType}"
//      + "&carTypes={carTypes}&couponMoney={couponMoney}&serverUrl={serverUrl}&appKey={appKey}";
  
  /**
   * 专车下单.
   */
  public static final String CREATE_ZCORDER = "api/orders/v4up/create";
  
  /**
   * 修改订单状态为接单.
   */
  public static final String UPDATE_STATUS_JIEDAN =
      "api/orders/update.json?appKey={appKey}&appId={appId}&sign={sign}&orderId={orderId}"
      + "&action={action}&employId={employId}&employName={employName}&employPhone={employPhone}"
      + "&employCompanyId={employCompanyId}&operator={operator}";
  /**
   * 修改订单状态为销单.
   */
  public static final String UPDATE_STATUS_CANCEL =
      "api/orders/update.json?appKey={appKey}&appId={appId}&sign={sign}&orderId={orderId}"
      + "&action={action}&operator={operator}&cause={cause}";
  /**
   * 修改订单状态为拒单.
   */
  public static final String UPDATE_STATUS_REFUSE =
      "api/orders/update.json?appKey={appKey}&appId={appId}&sign={sign}&orderId={orderId}"
      + "&employId={employId}&action={action}&operator={operator}&cause={cause}";
  /**
   * 到达目的地,开始等待.
   */
  public static final String UPDATE_STATUS_WAIT =
      "api/orders/update.json?appKey={appKey}&appId={appId}&sign={sign}&orderId={orderId}"
      + "&action={action}&operator={operator}";
  /**
   * 修改订单为正在执行.
   */
  public static final String UPDATE_STATUS_RUN =
      "api/orders/update.json?appKey={appKey}&appId={appId}&sign={sign}&orderId={orderId}"
      + "&action={action}&operator={operator}";
  /**
   * 修改订单为已完成.
   */
  public static final String UPDATE_STATUS_FINISH =
      "api/orders/update.json?appKey={appKey}&appId={appId}&sign={sign}&orderId={orderId}"
      + "&action={action}&operator={operator}";
  /**
   * 评价订单.
   */
  public static final String ORDER_REVIEW =
      "api/orderReview/review.json?orderId={orderId}&content={content}&score={score}"
      + "&appKey={appKey}&appId={appId}&sign={sign}";

  /**
   * 获取单个订单的评价
   */
  public static final String GET_ORDER_REVIEW = "api/orderReview/findReview";

  /**
   * 查询单个订单V4.
   */
  public static final String FIND_ONE_ORDER =
      "api/orders/v4/findByOrderId.json?orderId={orderId}&appKey={appKey}"
      + "&appId={appId}&sign={sign}";
  /**
   * V4查询车型.
   */
  public static final String QUERY_TYPE_V4 =
      "api/orders/v4/queryType?companyId={companyId}&appKey={appKey}&appId={appId}&sign={sign}";
  /**
   * 预约用车司机-我来做.
   */
  public static final String YUYUE_DRIVER_DO = "api/orders/v4/yuyueDriverDo";
  /**
   * V4接单.
   */
  public static final String UPDATE_JIEDAN_V4 = "api/orders/v4/jiedan";
  /**
   * V4拒接订单.
   */
  public static final String UPDATE_REFUSE_V4 = "api/orders/v4/refuse";
  /**
   * V4开始等待.
   */
  public static final String UPDATE_WAIT_V4 = "api/orders/v4/wait";
  /**
   * V4开始执行.
   */
  public static final String UPDATE_RUN_V4 = "api/orders/v4/run";
  /**
   * V4抢单.
   */
  public static final String UPDATE_GRAB_V4 = "api/orders/v4/grab";

  /**
   * V4追加专车订单.
   */
  public static final String CREATE_ORDERMORE_V4 = "api/orders/v4/createmore";
  /**
   * V4查询单个专车类型.
   */
  public static final String QUERY_ONE_CARTYPE_V4 = "api/orders/v4/queryOneType";
  /**
   * V4修改订单终点.
   */
  public static final String UPDATE_TOPLACE_V4 = "api/orders/v4/updateToPlace";
  /**
   * 查询未支付订单.
   */
  public static final String COUNT_NOTPAYAMOUNTS =
      "api/orders/countByPassengerId.json?passengerId={passengerId}"
      + "&appKey={appKey}&appId={appId}&sign={sign}";
  /**
   * 查询未完成订单.
   */
  public static final String COUNT_RUNNINGS =
      "api/orders/countRunning.json?passengerId={passengerId}"
      + "&appKey={appKey}&appId={appId}&sign={sign}";

  /**
   * 统计未完成订单.
   */
  public static final String FIND_RUNNINGS =
      "api/orders?passengerId={passengerId}&allstatus={allstatus}&appKey={appKey}";
  
  /**
   * 微信V5获取专车订单
   */
  public static final String GET_ORDERS_V5 = "api/orders/v4up/findOrdersV4up";
  
  /**
   * 专车预约订单
   */
  public static final String GET_YUYUE_ORDERS = "api/orders/findByParamsInBook";
  
  /**
   * 专车预约订单总数
   */
  public static final String GET_YUYUE_COUNT = "api/orders/countByParamsInBook";




  /**
   * 专车下单.
   * @param serverUrl 项目地址
   * @param appKey 系统key
   * @param ack ack
   * @param lat 纬度
   * @param lng 经度
   * @param passengerId 客户id
   * @param passengerPhone 客户手机
   * @param serverTime 预约时间
   * @param startAddress 开始地地址
   * @param startAddressDetail 开始地详细地址
   * @param startLat 开始地纬度
   * @param startLng 开始地经度
   * @param endAddress 结束地地址
   * @param endAddressDetail 结束地详细地址
   * @param endLat 结束地纬度
   * @param endLng 结束地经度
   * @param travelTime 行驶时间
   * @param mileage 行驶里程
   * @param flightNo 航班号
   * @param trainNo 班次好
   * @param serviceTypeId 类型id
   * @param serviceType 类型
   * @param carTypes 车型
   * @param couponMoney 优惠券金额
   * @param openId 微信openid
   */
  
  public String makeAnZhuancheAppointmentV4(String serverUrl, String appKey, String ack, Double lat,
      Double lng, Long passengerId, String passengerPhone, Long serverTime, String startAddress,
      String startAddressDetail, Double startLat, Double startLng, String endAddress,
      String endAddressDetail, Double endLat, Double endLng, Integer travelTime, Double mileage,
      String flightNo, String trainNo, Long serviceTypeId, String serviceType, String carTypes,
      Double couponMoney, String openId) {

    String passengerName = null;
    Long companyId = null;
    Long passengerCompanyId = null;
    String companyName = null;
    String channelName = null;
    if (StringUtils.isNotBlank(openId)) {
      channelName = "微信预约";
    } else {
      channelName = "网站预约";
    }
    
    Passenger passenger = passengerApi.findOne(passengerPhone, appKey);
    if (passenger != null) {
      passengerName = passenger.getName();
      passengerCompanyId = passenger.getCompanyId();
      passengerId = passenger.getId();
      JSONObject compay =
          daijiaApi.getCompanyIdAndName(serverUrl, appKey, passengerCompanyId, lng, lat);
      JSONObject jsonObject2 = compay.getJSONObject("data");

      companyId = jsonObject2.getLong("companyId");
      companyName = jsonObject2.getString("companyName");
    }else{
      JSONObject compay =
          daijiaApi.getCompanyIdAndName(serverUrl, appKey, null, lng, lat);
      JSONObject jsonObject2 = compay.getJSONObject("data");
      
      companyId = jsonObject2.getLong("companyId");
      companyName = jsonObject2.getString("companyName");
    }


    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

    kv.add("passengerId", String.valueOf(passengerId));
    kv.add("passengerPhone", passengerPhone);
    kv.add("passengerName", passengerName);
    kv.add("userPhone", passengerPhone);
    kv.add("companyId", String.valueOf(companyId));
    kv.add("companyName", companyName);
    kv.add("channelName", channelName);
    kv.add("serverTime", String.valueOf(serverTime));
    kv.add("startAddress", startAddress);
    kv.add("startAddressDetail", startAddressDetail);
    kv.add("startLat", String.valueOf(startLat));
    kv.add("startLng", String.valueOf(startLng));
    kv.add("endAddress", endAddress);
    kv.add("endAddressDetail", endAddressDetail);
    if(null!=endLat && null!=endLng){
      kv.add("endLat", String.valueOf(endLat));
      kv.add("endLng", String.valueOf(endLng));
    }
    if(null!=travelTime){
      kv.add("travelTime", String.valueOf(travelTime));
    }
    if(null!=mileage){
      kv.add("mileage", String.valueOf(mileage));
    }
    
    kv.add("prePay", "false");
    kv.add("flightNo", flightNo);
    kv.add("trainNo", trainNo);
    kv.add("serviceType", serviceType);
    kv.add("carTypes", carTypes);
    if(null!=couponMoney){
      kv.add("couponMoney", String.valueOf(couponMoney));
    }
    kv.add("serverUrl", serverUrl);
    kv.add("appKey", appKey);
    
//    String response =
//        restTemplate.postForObject(buildApi(CREATE_ZCORDER), null, String.class, passengerId,
//            passengerPhone, passengerName, passengerPhone, companyId, companyName, channelName,
//            serverTime, startAddress, startAddressDetail, startLat, startLng, endAddress,
//            endAddressDetail, endLat, endLng, travelTime, mileage, false, flightNo, trainNo,  
//            serviceType, carTypes, couponMoney, serverUrl, appKey);
    
    String response = postMultiValueMap(buildApi(CREATE_ZCORDER), kv);
        
    JSONObject jsonObject = JSON.parseObject(response);

    return response;
  }


  /**
   * 创建专车订单.
   * @param order 订单
   * @param passenger 客户
   * @param prePay 预付费
   * @param appKey 系统key
   */
  
  public JSONObject create(
      Order order, Passenger passenger, Boolean prePay, String appKey) throws Exception {
    Map<String, String> kv = new HashMap<>();
    StringBuilder builder = new StringBuilder();
    builder.append(buildApi(CREATE));
    kv.put("passengerId", String.valueOf(order.getPassengerId()));
    kv.put("passengerName", order.getPassengerName());
    kv.put("passengerPhone", order.getPassengerPhone());
    kv.put("showPhone", order.getShowPhone());
    if (null == order.getCompanyId() || StringUtils.isBlank(order.getCompanyName())) {
      kv.put("companyId", String.valueOf(passenger.getCompanyId()));
      kv.put("companyName", passenger.getCompanyName());
    } else {
      kv.put("companyId", String.valueOf(order.getCompanyId()));
      kv.put("companyName", order.getCompanyName());
    }
    kv.put("carTypeId", String.valueOf(order.getCarTypeId()));
    kv.put("channelName", order.getChannelName());
    kv.put("startAddress", order.getStartAddress());
    kv.put("startLat", String.valueOf(order.getStartLat()));
    kv.put("startLng", String.valueOf(order.getStartLng()));

    if (StringUtils.isNotBlank(order.getEndAddress())) {
      kv.put("endAddress", order.getEndAddress());
      builder.append("&endAddress={endAddress}");
    }
    if (StringUtils.isNotBlank(order.getEndAddressDetail())) {
      kv.put("endAddressDetail", order.getEndAddressDetail());
      builder.append("&endAddressDetail={endAddressDetail}");
    }
    if (order.getEndLat() != null) {
      kv.put("endLat", String.valueOf(order.getEndLat()));
      builder.append("&endLat={endLat}");
    }
    if (order.getEndLng() != null) {
      kv.put("endLng", String.valueOf(order.getEndLng()));
      builder.append("&endLng={endLng}");
    }

    kv.put("serverTime", String.valueOf(order.getServerTime().getTime()));
    if (order.getBudgetPay() != null) {
      kv.put("budgetPay", String.valueOf(order.getBudgetPay()));
      builder.append("&budgetPay={budgetPay}");
    }
    if (order.getShouldPay() != null) {
      kv.put("shouldPay", String.valueOf(order.getShouldPay()));
      builder.append("&shouldPay={shouldPay}");
    }
    if (order.getPrestartPrice() != null) {
      kv.put("preStartPrice", String.valueOf(order.getPrestartPrice()));
      builder.append("&preStartPrice={preStartPrice}");
    }
    if (order.getPremileagePrice() != null) {
      kv.put("preMileagePrice", String.valueOf(order.getPremileagePrice()));
      builder.append("&preMileagePrice={preMileagePrice}");
    }
    if (order.getPrerunTimePrice() != null) {
      kv.put("preRunTimePrice", String.valueOf(order.getPrerunTimePrice()));
      builder.append("&preRunTimePrice={preRunTimePrice}");
    }
    if (order.getPretravelTime() != null) {
      kv.put("preTravelTime", String.valueOf(order.getPretravelTime()));
      builder.append("&preTravelTime={preTravelTime}");
    }
    if (order.getPremileage() != null) {
      kv.put("preMileage", String.valueOf(order.getPremileage()));
      builder.append("&preMileage={preMileage}");
    }
    if (order.getCouponId() != null) {
      kv.put("couponId", String.valueOf(order.getCouponId()));
      builder.append("&couponId={couponId}");
    }
    kv.put("prePay", String.valueOf(prePay));

    if (StringUtils.isNotBlank(order.getStartAddressDetail())) {
      kv.put("startAddressDetail", order.getStartAddressDetail());
      builder.append("&startAddressDetail={startAddressDetail}");
    }
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
    ResponseEntity<String> responseEntity =
        restTemplate.postForEntity(builder.toString(), null, String.class, kv);
    if (responseEntity.getStatusCode().is2xxSuccessful()) {
      JSONObject json = (JSONObject) JSON.parse(responseEntity.getBody());
      return json;
    }
    return null;

  }

  /**
   * 查询车型V4.
   * @param companyId 公司id
   * @param appKey 系统key
   * @return JSONArray
   */
  
  public JSONArray getCarTypesV4(Long companyId, String appKey) {
    String response =
        restTemplate.getForObject(buildApi(GET_CARTYPEV4), String.class, companyId, appKey);

    JSONObject jsonObject = JSON.parseObject(response);
    JSONArray jsonArray = jsonObject.getJSONArray("data");

    return jsonArray;
  }

  /**
   * 查询收费id.
   * 
   * @param typeId 类型id
   * @param appKey 系统key
   * @return JSONObject
   */
  public JSONObject queryAreaId(Long typeId, String appKey) {
    String response =
        restTemplate.getForObject(buildApi(QUERY_AREABYTYPEID), String.class, typeId, appKey);

    JSONObject jsonObject = JSON.parseObject(response);

    return jsonObject;
  }

  /**
   * 根据groupId查询订单.
   * 
   * @param groupId groupId
   * @param appKey 系统key
   * @return JSONArray
   */
  public JSONArray findGroupIdV4(Long groupId, String appKey) {
    String response =
        restTemplate.getForObject(buildApi(FIND_BYGROUPID), String.class, groupId, appKey);

    JSONObject jsonObject = JSON.parseObject(response);
    JSONArray jsonArray = jsonObject.getJSONArray("data");

    return jsonArray;
  }

  /**
   * 根据主键查询订单信息.
   * 
   * @param orderId 订单id
   * @param appKey 系统key
   * @return Order
   */
  public Order findById(Long orderId, String appKey) throws Exception {

    Map<String, String> kv = new HashMap<String, String>();
    kv.put("orderId", String.valueOf(orderId));
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    String result = restTemplate.getForObject(buildApi(FIND_BY_ID), String.class, kv);

    JSONObject jo = JSON.parseObject(result);
    Order order = null;
    if (jo.getIntValue("code") == 0) {
      order = jo.getObject("data", Order.class);
    }

    return order;
  }

  /**
   * 查询订单.
   * @param passengerId 客户id
   * @param page 页数
   * @param rows 每页数量
   * @param status 状态
   * @param appKey 系统key
   */
  
  public DataGrid<Map<String, Object>> findByParam(
      Long passengerId, Integer page, Integer rows, String status, String appKey) {
    Long total = 0L;
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("passengerId", String.valueOf(passengerId));
    kv.put("page", String.valueOf(page));
    kv.put("rows", String.valueOf(rows));
    kv.put("orderby", "status asc,finishTime desc,serverTime asc");
    kv.put("status", status);
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    String result = restTemplate.getForObject(buildApi(FIND_BY_PARAM), String.class, kv);
    JSONObject object = JSON.parseObject(result);
    int code = object.getInteger("code");
    if (code == 0) {
      JSONObject json = object.getJSONObject("data");
      total = json.getLong("total");
      List<Order> orders = new ArrayList<Order>();
      JSONArray jsonArray = json.getJSONArray("rows");
      orders = JSON.parseArray(jsonArray.toString(), Order.class);
      for (Order order : orders) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", order.getId());
        map.put("orderNo", order.getOrderNo());
        map.put("passengerPhone", order.getPassengerPhone());
        map.put("showPhone", order.getShowPhone());
        map.put("startAddress", order.getStartAddress());
        map.put("startAddressDetail", order.getStartAddressDetail());
        map.put("startLat", order.getStartLat());
        map.put("startLng", order.getStartLng());
        map.put("endAddress", order.getEndAddress());
        map.put("endAddressDetail", order.getEndAddressDetail());
        map.put("endLat", order.getEndLat());
        map.put("endLng", order.getEndLng());
        map.put("status", order.getStatus());
        map.put("serverTime", order.getServerTime().getTime());
        map.put("review", order.getReview());
        map.put("treatment", order.getTreatment());
        map.put("budgetPay", order.getBudgetPay());
        map.put("startPrice", order.getStartPrice());
        map.put("mileagePrice", order.getMileagePrice());
        map.put("runTimePrice", order.getRunTimePrice());
        map.put("mileage", order.getMileage());
        map.put("runTime", order.getRunTime());
        map.put("realPay", order.getRealPay());
        map.put("orderMemos", order.getOrderMemos());
        map.put("companyId", order.getCompanyId());
        map.put("companyName", order.getCompanyName());
        map.put("employId", order.getEmployId());
        map.put("employName", order.getEmployName());// 昵称
        map.put("employPhone", order.getEmployPhone());
        map.put("employNo", order.getEmployNo());// 工号
        map.put("employPhoto", order.getEmployPhoto());
        map.put("employScore", order.getEmployScore());
        map.put("employCompanyId", order.getEmployCompanyId());
        map.put("carNumber", order.getCarNumber());
        map.put("carName", order.getCarName());
        if (order.getOrderReview() != null) {
          map.put("orderScore", order.getOrderReview().getScore());
          map.put("orderContent", order.getOrderReview().getContent());
        }
        map.put("carTypeName", order.getCarTypeName());
        list.add(map);
      }
    }
    DataGrid<Map<String, Object>> dataGrid = new DataGrid<Map<String, Object>>();
    dataGrid.setTotal(total);
    dataGrid.setRows(list);
    return dataGrid;
  }

  /**
   * 催一下订单进度.
   * 
   * @param orderId 订单id
   * @param appKey 系统key
   * @return String
   */
  public String hasten(Long orderId, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("orderId", String.valueOf(orderId));
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);
    String result = restTemplate.getForObject(buildApi(HASTEN_ORDER), String.class, kv);
    JSONObject jo = JSON.parseObject(result);

    if (jo.getIntValue("code") == 0) {
      return "success";
    } else {
      return "fail";
    }
  }

  /**
   * 修改订单状态为接单.
   * @param orderId 订单id
   * @param employId 服务人员id
   * @param employName 服务人员名称
   * @param employPhone 服务人员电话
   * @param employCompanyId 服务人员公司id
   * @param employNo 服务人员编号
   * @param employPhoto 服务人员头像
   * @param employScore 服务人员来源
   * @param operator 操作人
   * @param appKey 系统key
   */
  public void updateToJiedan(Long orderId, Long employId, String employName, String employPhone,
      Long employCompanyId, String employNo, String employPhoto, Double employScore,
      String operator, String appKey) {

    Map<String, String> kv = new HashMap<String, String>();
    String url = buildApi(UPDATE_STATUS_JIEDAN);
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    kv.put("orderId", String.valueOf(orderId));
    kv.put("action", "jiedan");
    kv.put("employId", String.valueOf(employId));
    kv.put("employName", employName);
    kv.put("employPhone", employPhone);
    kv.put("employCompanyId", String.valueOf(employCompanyId));
    kv.put("operator", operator);
    if (StringUtils.isNotBlank(employNo)) {
      kv.put("employNo", employNo);
      url += "&employNo={employNo}";
    }
    if (StringUtils.isNotBlank(employPhoto)) {
      kv.put("employPhoto", employPhoto);
      url += "&employPhoto={employPhoto}";
    }
    if (employScore != null) {
      kv.put("employScore", String.valueOf(employScore));
      url += "&employScore={employScore}";
    }
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);
    restTemplate.put(url, null, kv);
  }

  /**
   * 修改订单状态为销单.
   * @param orderId 订单id
   * @param cause 销单备注
   * @param operator 操作人
   * @param appKey 系统key
   */
  public void updateToCancel(Long orderId, String cause, String operator, String appKey) {

    Map<String, String> kv = new HashMap<String, String>();
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    kv.put("orderId", String.valueOf(orderId));
    kv.put("action", "cancel");
    kv.put("cause", cause);
    kv.put("operator", operator);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    restTemplate.put(buildApi(UPDATE_STATUS_CANCEL), null, kv);
  }

  /**
   * 修改订单状态为拒单.
   * 
   * @param orderId 订单id
   * @param employId 服务人员id
   * @param cause 拒单备注
   * @param operator 操作人
   * @param appKey 系统key
   */
  public void updateToRefuse(Long orderId, Long employId, String cause, String operator,
      String appKey) {

    Map<String, String> kv = new HashMap<String, String>();
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    kv.put("orderId", String.valueOf(orderId));
    kv.put("employId", String.valueOf(employId));
    kv.put("action", "refuse");
    kv.put("cause", cause);
    kv.put("operator", operator);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    restTemplate.put(buildApi(UPDATE_STATUS_REFUSE), null, kv);
  }

  /**
   * 到达目的地,开始等待.
   * 
   * @param orderId 订单id
   * @param operator 操作人
   * @param appKey 系统key
   */
  public void updateToWait(Long orderId, String operator, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    kv.put("orderId", String.valueOf(orderId));
    kv.put("action", "wait");
    kv.put("operator", operator);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    restTemplate.put(buildApi(UPDATE_STATUS_WAIT), null, kv);
  }

  /**
   * 修改订单为正在执行.
   * 
   * @param orderId 订单id
   * @param operator 操作人
   * @param appKey 系统key
   */
  public void updateToRun(Long orderId, String operator, String appKey) {

    Map<String, String> kv = new HashMap<String, String>();
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    kv.put("orderId", String.valueOf(orderId));
    kv.put("action", "run");
    kv.put("operator", operator);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    restTemplate.put(buildApi(UPDATE_STATUS_RUN), null, kv);
  }

  /**
   * 修改订单为已完成.
   * 
   * @param orderId 订单id
   * @param operator 操作人
   * @param appKey 系统key
   */
  public void updateToFinish(Long orderId, String operator, String appKey) {

    Map<String, String> kv = new HashMap<String, String>();
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    kv.put("orderId", String.valueOf(orderId));
    kv.put("action", "finish");
    kv.put("operator", operator);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    restTemplate.put(buildApi(UPDATE_STATUS_FINISH), null, kv);
  }

  /**
   * 评价订单.
   * 
   * @param orderId 订单id
   * @param score 评价等级
   * @param content 备注
   * @param appKey 系统key
   * @return JSONObject
   */
  public JSONObject review(Long orderId, double score, @RequestParam(value = "content", required = false)String content, String appKey) {
    Map<String, String> kv = new HashMap<>();
    kv.put("orderId", String.valueOf(orderId));
    kv.put("score", String.valueOf(score));
    kv.put("content", content);
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    ResponseEntity<String> responseEntity =
        restTemplate.postForEntity(buildApi(ORDER_REVIEW), null, String.class, kv);

    if (responseEntity.getStatusCode().is2xxSuccessful()) {
      return (JSONObject) JSON.parse(responseEntity.getBody());
    }

    return null;
  }
  
  /**
   * 封装多部件请求.
   */
  
  public String postMultiValueMap(String url, MultiValueMap<String, String> kv) {
    Set<Entry<String, List<String>>> entries = kv.entrySet();

    Map<String, String> params = new HashMap<String, String>();
    for (Entry<String, List<String>> entry : entries) {
      List<String> values = entry.getValue();
      params.put(entry.getKey(), CollectionUtils.isEmpty(values) ? null : values.get(0));
    }

    String sign = SignHelper.sign(SignHelper.buildSignMessage(params), zhuanAppKey);

    kv.add("sign", sign);
    kv.add("appId", zhuanAppId);

    return restTemplate.postForObject(url, kv, String.class);
  }

  private String buildApi(String api) {
    StringBuilder builder = new StringBuilder();
    builder.append(zhuanApiGateway);
    if (!zhuanApiGateway.endsWith("/")) {
      builder.append("/");
    }
    builder.append(api);

    return builder.toString();
  }

  private String buildApiDaijia(String server, String api) {

    StringBuilder builder = new StringBuilder();

    String daijiaServer = StringUtils.trimToEmpty(server).toLowerCase();
    if (!daijiaServer.startsWith("http://") && !daijiaServer.startsWith("https://")) {
      builder.append("http://");
    }
    builder.append(daijiaServer);
    if (!daijiaServer.endsWith("/")) {
      builder.append("/");
    }

    if (StringUtils.isNotBlank(api)) {
      builder.append(api);
    }

    return builder.toString();
  }

  /**
   * 查询单个订单V4.
   * 
   * @param orderId 订单id
   * @param address 代驾系统地址
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport findOneV4(Long orderId, String address, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("orderId", String.valueOf(orderId));
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    String result = restTemplate.getForObject(buildApi(FIND_ONE_ORDER), String.class, kv);
    ResultTransport orderTransport = JSON.parseObject(result, ResultTransport.class);
    if (orderTransport.getCode() == 0) {
      Map<String, Object> map = (Map<String, Object>) orderTransport.getData();

      Object object2 = map.get("areaId");
      map.remove("areaId");
      Long areaId = Long.valueOf(object2.toString());
      if (areaId != null) {
        StringBuilder builder2 = new StringBuilder();
        builder2.append(buildApiDaijia(address,
            "api/company/v4/findChargeStartTimes.json?areaId={areaId}"));
        String result2 = restTemplate.getForObject(builder2.toString(), String.class, areaId);
        ResultTransport areaTransport = JSON.parseObject(result2, ResultTransport.class);
        if (areaTransport.getCode() == 0) {
          List<ChargeStartTime> chargeStartTimes =
              JSON.parseArray(areaTransport.getData().toString(), ChargeStartTime.class);
          map.put("chargeStartTimes", chargeStartTimes);
        }
      }
      orderTransport.setData(map);
    }
    return orderTransport;
  }
  
  /**
   * 预约用车司机-我来做.
   * 
   * @param orderId 订单id
   * @param appKey 系统key
   * @param appKey2 
   * @return ResultTransport
   */
  public ResultTransport yuyueDriverDo(Long orderId, Long employId, String appKey, String serverUrl) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    
    kv.add("appKey", appKey);
    kv.add("orderId", String.valueOf(orderId));
    kv.add("employId", String.valueOf(employId));
    kv.add("serverUrl", serverUrl);

    String result = postMultiValueMap(buildApi(YUYUE_DRIVER_DO), kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }
  
  /**
   * V4接单.
   * 
   * @param orderId 订单id
   * @param appKey 系统key
   * @param appKey2 
   * @return ResultTransport
   */
  public ResultTransport updateToJiedanV4(Long orderId, Long employId, String appKey, String serverUrl) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    
    kv.add("appKey", appKey);
    kv.add("orderId", String.valueOf(orderId));
    kv.add("employId", String.valueOf(employId));
    kv.add("serverUrl", serverUrl);

    String result = postMultiValueMap(buildApi(UPDATE_JIEDAN_V4), kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }

  /**
   * V4拒接订单.
   * 
   * @param orderId 订单id
   * @param employId 服务人员id
   * @param cause 拒单理由
   * @param operator 操作人
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport refuseV4(Long orderId, Long employId, String cause, String operator,
      String appKey) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    kv.add("appKey", appKey);

    kv.add("orderId", String.valueOf(orderId));
    kv.add("employId", String.valueOf(employId));
    kv.add("cause", cause);
    kv.add("operator", operator);

    String result = postMultiValueMap(buildApi(UPDATE_REFUSE_V4), kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }

  /**
   * V4查询车型.
   * 
   * @param companyId 公司id
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport queryTypeV4(Long companyId, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("companyId", String.valueOf(companyId));
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    String result = restTemplate.getForObject(buildApi(QUERY_TYPE_V4), String.class, kv);
    ResultTransport parseObject = JSON.parseObject(result, ResultTransport.class);
    return parseObject;
  }

  /**
   * V4查询单个专车类型.
   * 
   * @param carTypeId 车型id
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport queryOneType(Long carTypeId, String appKey) {
    Map<String, String> kv = new HashMap<String, String>();
    kv.put("carTypeId", String.valueOf(carTypeId));
    kv.put("appKey", appKey);
    kv.put("appId", zhuanAppId);
    String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
    kv.put("sign", sign);

    String result = restTemplate.getForObject(buildApi(QUERY_ONE_CARTYPE_V4), String.class, kv);
    ResultTransport parseObject = JSON.parseObject(result, ResultTransport.class);
    return parseObject;
  }

  /**
   * V4开始等待.
   * 
   * @param orderId 订单id
   * @param operator 操作人
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport waitV4(Long orderId, String operator, String appKey, String serverUrl) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    kv.add("orderId", String.valueOf(orderId));
    kv.add("operator", operator);
    kv.add("appKey", appKey);
    kv.add("serverUrl", serverUrl);

    String result = postMultiValueMap(buildApi(UPDATE_WAIT_V4), kv);

    ResultTransport parseObject = JSON.parseObject(result, ResultTransport.class);

    return parseObject;
  }

  /**
   * V4开始执行.
   * 
   * @param orderId 订单id
   * @param operator 操作人
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport runV4(Long orderId, String operator, String appKey,
      String realStartAddress,Double realStartLat,Double realStartLng) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    kv.add("orderId", String.valueOf(orderId));
    kv.add("operator", operator);
    kv.add("appKey", appKey);

    if (StringUtils.isNotBlank(realStartAddress)) {
      kv.add("realStartAddress", realStartAddress);
    }
    if (null != realStartLat) {
      kv.add("realStartLat", String.valueOf(realStartLat));
    }
    if (null != realStartLng) {
      kv.add("realStartLng", String.valueOf(realStartLng));
    }
    
    String result = postMultiValueMap(buildApi(UPDATE_RUN_V4), kv);

    ResultTransport parseObject = JSON.parseObject(result, ResultTransport.class);

    return parseObject;
  }

  /**
   * V4抢单.
   * 
   * @param orderId 订单id
   * @param employId 服务人员id
   * @param employName 服务人员名字
   * @param employPhone 服务人员电话
   * @param companyId 公司id
   * @param employAccount 服务人员余额
   * @param employPhoto 服务人员照片
   * @param employScore 服0务人员等级
   * @param operator 操作人
   * @param rentCompanyId 
   * @param appKey 系统key
   * @param appKey 
   * @return ResultTransport
   */
  public ResultTransport grabV4(
      Long orderId, Long employId, String employName, String employPhone,
      Long companyId, String employAccount, String employPhoto, Double employScore,
      String operator, Long rentalCompanyId, String rentalCompanyName, String appKey) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    kv.add("orderId", String.valueOf(orderId));
    kv.add("appKey", appKey);
    kv.add("orderId", String.valueOf(orderId));
    kv.add("employId", String.valueOf(employId));
    kv.add("employName", employName);
    kv.add("employPhone", employPhone);
    kv.add("employCompanyId", String.valueOf(companyId));
    kv.add("operator", operator);
    kv.add("employNo", employAccount);
    kv.add("employScore", String.valueOf(employScore));
    if (StringUtils.isNotBlank(employPhoto)) {
      kv.add("employPhoto", employPhoto);
    }
    if(null!=rentalCompanyId){
      kv.add("rentalCompanyId", String.valueOf(rentalCompanyId));
    }
    if (StringUtils.isNotBlank(rentalCompanyName)) {
      kv.add("rentalCompanyName", rentalCompanyName);
    }
    
    
    String result = postMultiValueMap(buildApi(UPDATE_GRAB_V4), kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);
    

    return resultTransport;
  }

  /**
   * V4修改订单终点.
   * 
   * @param orderId 订单id
   * @param toPlace 目的地
   * @param longitude 经度
   * @param latitude 纬度
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport updateToPlaceV4(Long orderId, String toPlace, Double longitude,
      Double latitude, String appKey) {
    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
    kv.add("orderId", String.valueOf(orderId));
    kv.add("toPlace", toPlace);
    kv.add("longitude", String.valueOf(longitude));
    kv.add("latitude", String.valueOf(latitude));
    kv.add("appKey", appKey);

    String result = postMultiValueMap(buildApi(UPDATE_TOPLACE_V4), kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }

  /**
   * V4追加专车订单.
   * 
   * @param passengerPhone 客户电话
   * @param carTypeId 车型id
   * @param startAddress 开始地点
   * @param startLat 开始纬度
   * @param startLng 开始经度
   * @param employId 服务人员id
   * @param employName 服务人员名称
   * @param employPhone 服务人员手机
   * @param companyId 公司id
   * @param appKey 系统key
   * @return ResultTransport
   */
  public ResultTransport createmoreV4(String passengerPhone, Long carTypeId, String startAddress,
      Double startLat, Double startLng, Long employId, String employName, String employPhone,
      Long companyId, String appKey) {

    MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

    kv.add("passengerPhone", passengerPhone);
    kv.add("appKey", appKey);
    kv.add("carTypeId", String.valueOf(carTypeId));
    kv.add("startAddress", startAddress);
    kv.add("startLat", String.valueOf(startLat));
    kv.add("startLng", String.valueOf(startLng));
    kv.add("employId", String.valueOf(employId));
    kv.add("employName", employName);
    kv.add("employPhone", employPhone);
    kv.add("employCompanyId", String.valueOf(companyId));

    String result = postMultiValueMap(buildApi(CREATE_ORDERMORE_V4), kv);

    ResultTransport resultTransport = JSON.parseObject(result, ResultTransport.class);

    return resultTransport;
  }

  /**
   * 查询未支付订单.
   * 
   * @param passengerId 客户id
   * @param appKey 系统key
   * @return Long
   */
  public Long countNotPayAmounts(Long passengerId, String appKey) {
    Long num = 0L;
    try {
      Map<String, String> kv = new HashMap<String, String>();
      kv.put("passengerId", String.valueOf(passengerId));
      kv.put("appKey", appKey);
      kv.put("appId", zhuanAppId);
      String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
      kv.put("sign", sign);
      String result = restTemplate.getForObject(buildApi(COUNT_NOTPAYAMOUNTS), String.class, kv);
      JSONObject object = JSON.parseObject(result);
      int code = object.getInteger("code");
      if (code == 0) {
        num = object.getLongValue("data");
      }
    } catch (Exception ex) {
      logger.error(ex.getMessage());
    }
    return num;
  }

  /**
   * 统计未完成订单.
   * 
   * @param passengerId 客户id
   * @param appKey 系统key
   * @return Long
   */
  public Long countRunning(Long passengerId, String appKey) {
    Long num = 0L;
    try {
      Map<String, String> kv = new HashMap<String, String>();
      kv.put("passengerId", String.valueOf(passengerId));
      kv.put("appKey", appKey);
      kv.put("appId", zhuanAppId);
      String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
      kv.put("sign", sign);
      String result = restTemplate.getForObject(buildApi(COUNT_RUNNINGS), String.class, kv);
      JSONObject object = JSON.parseObject(result);
      int code = object.getInteger("code");
      if (code == 0) {
        num = object.getLongValue("data");
      }
    } catch (Exception ex) {
      logger.error(ex.getMessage());
    }

    return num;
  }

  /**
   * 统计未完成订单.
   * 
   * @param passengerId 客户id
   * @param appKey 系统key
   * @return JSONArray
   */
  public JSONArray findRunning(Long passengerId, String appKey) {

    Map<String, String> kv = new HashMap<String, String>();
    kv.put("passengerId", String.valueOf(passengerId));
    kv.put("allstatus", "0,1,2,3,4");
    kv.put("appKey", appKey);

    String result = restTemplate.getForObject(buildApi(FIND_RUNNINGS), String.class, kv);
    JSONObject object = JSON.parseObject(result);
    int code = object.getInteger("code");
    JSONArray jsonArray = null;
    if (code == 0) {
      JSONObject json = object.getJSONObject("data");
      jsonArray = json.getJSONArray("rows");
    }
    return jsonArray;
  }
 
  /**
	 * 专车预约订单（下单）
	 * @param passengerId 用户id
	 * @param passengerPhone 用户电话
	 * @param passengerName 用户名称
	 * @param userPhone 若为其他人下单，则，这里是其他人的电话
	 * @param companyId 公司id
	 * @param companyName 公司名称
	 * @param serverTime 服务时间
	 * @param startAddress 开始地址信息
	 * @param startAddressDetail 开始地址详细信息
	 * @param startLat 开始lat
	 * @param startLng 开始lng
	 * @param carTypes 车辆类型集合
	 * @param appKey 系统Key
	 * @param endAddress 结束地址
	 * @param endAddressDetail 结束地址详细信息
	 * @param endLat 结束lat
	 * @param endLng 结束lng
	 * @param travelTime 服务时长（预算接口返回）
	 * @param mileage 公里数
	 * @param prePay 是否预支付
	 * @param memo 用车需求
	 * @param flightNo 航班号
	 * @param trainNo 车次号
	 * @param operator 操作人
	 * @param serviceTypeId 服务类型id
	 * @param serviceType 服务类型
	 * @param serverUrl 代驾项目服务器地址
	 * @param couponIds 后台传的参数
	 * @param couponMoney 优惠券各车型优惠的总金额
	 * @param createOrderName 创建的订单名称
	 * @param channelName 渠道名称
	 * @return
	 * @throws Exception
	 */
  public String createOrderV5 (
		  Long passengerId,
	      String passengerPhone,
	      String passengerName,
	      String userPhone,
	      Long companyId,
	      String companyName,
	      String channelName,
	      Long serverTime,
	      String startAddress,
	      Double startLat,
	      Double startLng,
	      String appKey,
	      String carTypes,
	      String startAddressDetail,
	      String endAddress,
	      String endAddressDetail,
	      Double endLat,
	      Double endLng,
	      Integer travelTime,
	      Double mileage,
	      Boolean prePay,
	      String memo,
	      String flightNo,
	      String trainNo,
	      String operator,
	      Long serviceTypeId,
	      String serviceType,
	      String serverUrl,
	      String couponIds,
	      Double couponMoney,
	      String createOrderName,
          Long driverId
		  ) throws Exception {
	  
	  // 设置参数
	  MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
	  if (null != passengerId) {
		  kv.add("passengerId", String.valueOf(passengerId));
	  }
	  if (null != passengerPhone) {
		  kv.add("passengerPhone", String.valueOf(passengerPhone));
	  }
	  if (null != passengerName) {
		  kv.add("passengerName", String.valueOf(passengerName));
	  }
	  if (null != userPhone && !userPhone.isEmpty()) {
		  kv.add("userPhone", String.valueOf(userPhone));
	  }
	  if (null != companyId) {
		  kv.add("companyId", String.valueOf(companyId));
	  }
	  if (null != companyName) {
		  kv.add("companyName", String.valueOf(companyName));
	  }
	  if (null != channelName) {
		  kv.add("channelName", String.valueOf(channelName));
	  }
	  if (null != serverTime) {
		  kv.add("serverTime", String.valueOf(serverTime));
	  }
	  if (null != startAddress) {
		  kv.add("startAddress", String.valueOf(startAddress));
	  }
	  if (null != startLat) {
		  kv.add("startLat", String.valueOf(startLat));
	  }
	  if (null != startLng) {
		  kv.add("startLng", String.valueOf(startLng));
	  }
	  if (null != startAddressDetail) {
		  kv.add("startAddressDetail", String.valueOf(startAddressDetail));
	  }
	  if (null != endAddress) {
		  kv.add("endAddress", String.valueOf(endAddress));
	  }
	  if (null != endAddressDetail) {
		  kv.add("endAddressDetail", String.valueOf(endAddressDetail));
	  }
	  if (null != endLat) {
		  kv.add("endLat", String.valueOf(endLat));
	  }
	  if (null != endLng) {
		  kv.add("endLng", String.valueOf(endLng));
	  }
	  if (null != travelTime) {
		  kv.add("travelTime", String.valueOf(travelTime));
	  }
	  if (null != mileage) {
		  kv.add("mileage", String.valueOf(mileage));
	  }
	  if (null != prePay) {
		  kv.add("prePay", String.valueOf(prePay));
	  }
	  if (null != memo) {
		  kv.add("memo", String.valueOf(memo));
	  }
	  if (null != flightNo && !flightNo.isEmpty()) {
		  kv.add("flightNo", String.valueOf(flightNo));
	  }
	  if (null != trainNo && !trainNo.isEmpty()) {
		  kv.add("trainNo", String.valueOf(trainNo));
	  }
	  if (null != operator) {
		  kv.add("operator", String.valueOf(operator));
	  }
	  if (null != serviceTypeId) {
		  kv.add("serviceTypeId", String.valueOf(serviceTypeId));
	  }
	  if (null != serviceType) {
		  kv.add("serviceType", String.valueOf(serviceType));
	  }
	  if (null != carTypes) {
		  kv.add("carTypes", String.valueOf(carTypes));
	  }
	  if (null != serverUrl) {
		  kv.add("serverUrl", String.valueOf(serverUrl));
	  }
	  if (null != couponIds) {
		  kv.add("couponIds", String.valueOf(couponIds));
	  }
	  if (null != couponMoney) {
		  kv.add("couponMoney", String.valueOf(couponMoney));
	  }
	  if (null != createOrderName) {
		  kv.add("createOrderName", String.valueOf(createOrderName));
	  }
	  if (null != appKey) {
		  kv.add("appKey", String.valueOf(appKey));
	  }
	  if (null != driverId) {
		  kv.add("driverId", String.valueOf(driverId));
	  }

	  // 请求并返回
	  String rs = postMultiValueMap(buildApi(CREATE_ZCORDER), kv);
	  System.out.println("下单返回 ==> " + rs);
	  return rs;
  }

  /**
   * 专车获取所有订单订单
   * @param passengerId 乘客ID
   * @param page 页码
   * @param rows 数据条数
   * @param status 订单状态
   * @param appKey 系统KEY
   * @return
   * @throws Exception 
   */
  public Map<String, Object> getOrdersV5 (Long passengerId, Integer page, 
		  Integer rows, String status, String appKey) throws Exception {

		DataGrid<Map<String, Object>> dataGrid = new DataGrid<Map<String, Object>>();
		Map<String, Object> returnMap = new HashMap<String, Object>();

		final String api = GET_ORDERS_V5 
				+ "?passengerId={passengerId}"
				+ "&page={page}"
				+ "&rows={rows}"
				+ "&status={status}"
				+ "&appKey={appKey}";

		String rs = restTemplate.getForObject(buildApi(api), String.class, passengerId, page, rows, status, appKey);
		JSONObject json = JSONObject.parseObject(rs);
		if (json.getIntValue("code") != 0) {
			throw new RuntimeException();
		}

		JSONObject data = json.getJSONObject("data");
		returnMap.put("total", data.getInteger("total"));
		returnMap.put("rows", data.getJSONArray("rows"));
		return returnMap;
  }

  /**
   * 获取单个订单的评价
   * @param appKey
   * @param orderId
   * @return
   */
  public JSONObject getReviewByOrderId (String appKey, Long orderId) {

	  Map<String, Object> returnMap = new HashMap<String, Object>();
	  
	  final String api = GET_ORDER_REVIEW 
			  + "?orderId={orderId}"
			  + "&appKey={appKey}"
			  + "&appId={appId}"
			  + "&sign={sign}";
	  
	  Map<String, String> kv = new HashMap<>();
	  kv.put("orderId", String.valueOf(orderId));
	  kv.put("appKey", appKey);
	  kv.put("appId", zhuanAppId);
	  String sign = SignHelper.sign(SignHelper.buildSignMessage(kv), zhuanAppKey);
	  kv.put("sign", sign);

	  ResponseEntity<String> responseEntity = restTemplate.getForEntity(buildApi(api), String.class, kv);

	  if (responseEntity.getStatusCode().is2xxSuccessful()) {
	      return (JSONObject) JSON.parse(responseEntity.getBody());
	  }
	  return null;
  }
  
  /**
   * 查询预约订单
   * 
   * @param page
   * @param rows
   * @param latitude
   * @param longitude
   * @param serverUrl
   * @param carTypeId
   * @param appKey
   * @return
   */
  public ResultTransport findByParamsInBook(Integer page, Integer rows,
			Double latitude, Double longitude, String serverUrl, Integer carTypeId,
			String appKey) {
	Map<String, Object> kv = new HashMap<String, Object>();
	
	final String api = GET_YUYUE_ORDERS 
			  + "?appKey={appKey}"
			  + "&page={page}"
			  + "&rows={rows}"
			  + "&latitude={latitude}"
			  + "&longitude={longitude}"
			  + "&carTypeId={carTypeId}"
			  + "&serverUrl={serverUrl}";

    kv.put("page", String.valueOf(page));
    kv.put("rows", String.valueOf(rows));
    kv.put("latitude", String.valueOf(latitude));
    kv.put("longitude", String.valueOf(longitude));
    kv.put("carTypeId", String.valueOf(carTypeId));
    kv.put("appKey", appKey);
    kv.put("serverUrl", serverUrl);

    ResponseEntity<String> responseEntity = restTemplate.getForEntity(buildApi(api), String.class, kv);
    
    JSONObject object = JSON.parseObject(responseEntity.getBody().toString()); 

    ResultTransport resultTransport = JSON.parseObject(responseEntity.getBody(), ResultTransport.class);

    return resultTransport;
  }
  
  /**
   * 查询总预约订单数量 
   * 
   * @param latitude
   * @param longitude
   * @param serverUrl
   * @param carTypeId
   * @param appKey
   * @return
   */
  public ResultTransport countByParamsInBook(Double latitude, Double longitude, String serverUrl, Integer carTypeId,
 String appKey) {
		Map<String, Object> kv = new HashMap<String, Object>();

		final String api = GET_YUYUE_COUNT + "?appKey={appKey}"
				+ "&latitude={latitude}" + "&longitude={longitude}"
				+ "&carTypeId={carTypeId}" + "&serverUrl={serverUrl}";

		kv.put("latitude", String.valueOf(latitude));
		kv.put("longitude", String.valueOf(longitude));
		kv.put("carTypeId", String.valueOf(carTypeId));
		kv.put("appKey", appKey);
		kv.put("serverUrl", serverUrl);

		ResponseEntity<String> responseEntity = restTemplate.getForEntity(
				buildApi(api), String.class, kv);

		ResultTransport resultTransport = JSON.parseObject(
				responseEntity.getBody(), ResultTransport.class);

		return resultTransport;
	}
}
